import uuid
import datetime
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.generics import GenericAPIView
from api.extension import mixins
from api.serializers import account
from django.db.models import Q
from api import models
from rest_framework.response import Response


# 用户注册
class RegisterView(mixins.DigCreateModelMixin, GenericAPIView, ViewSet):
    authentication_classes = []
    permission_classes = []
    serializer_class = account.RegisterSerializer

    def perform_create(self, serializer):
        serializer.validated_data.pop('confirm_password')
        serializer.save()


# 用户登录

class AuthView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        # 获取序列化数据，和数据库中进行校验
        serializer = account.AuthSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({'code': 2001, 'detail': serializer.errors})
        username = serializer.validated_data.get('username')
        phone = serializer.validated_data.get('phone')
        password = serializer.validated_data.get('password')

        user_obj = models.UserInfo.objects.filter(Q(Q(username=username) | Q(phone=phone)),
                                                  password=password).first()
        if not user_obj:
            return Response({'code': 2001, 'detail': '用户名或密码错误'})

        # 给登录用户 生产成一个有效期的token
        token = str(uuid.uuid4())
        user_obj.token = token
        # 设置有效期 为两周
        user_obj.token_expiry_date = datetime.datetime.now() + datetime.timedelta(weeks=2)
        user_obj.save()

        return Response({'code': 0, 'data': {'token': user_obj.token, 'name': user_obj.username}})
